package org.example.annotation;

import org.springframework.util.StringUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.text.SimpleDateFormat;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Package:                 com.bill99.fto.cmdc.pay.common.annotation
 * Date:                    2019/4/25 17:50
 * @Author:                kevin.wang
 * Company:                 kuaiqian
 * Version:                 1.0.0
 * Description:             类
 */
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = DatePattern.DateValidator.class)
public @interface DatePattern {

    String message() default "日期格式不正确";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String pattern() default "yyyy-MM-dd HH:mm:ss";

    public class DateValidator implements ConstraintValidator<DatePattern, Object> {
        private String pattern;

        @Override
        public void initialize(DatePattern constraint) {
            pattern = constraint.pattern();
        }

        @Override
        public boolean isValid(Object strDate, ConstraintValidatorContext context) {
            if(StringUtils.isEmpty(strDate)){
                return Boolean.TRUE;
            }
            try {
                String dataString = strDate.toString();
                SimpleDateFormat format = new SimpleDateFormat(pattern);
                format.parse(dataString);
                return Boolean.TRUE;
            } catch (Exception e) {
                return Boolean.FALSE;
            }
        }
    }
}
